<template>
  <el-dialog
    :model-value="visible"
    :title="modalTitle"
    width="600px"
    @update:model-value="handleVisibleChange"
    @close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="物品标题" prop="title">
        <el-input
          v-model="formState.title"
          placeholder="请输入物品标题"
          :maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="物品描述" prop="description">
        <el-input
          v-model="formState.description"
          type="textarea"
          placeholder="请输入物品描述"
          :rows="4"
          :maxlength="255"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="物品分类" prop="category">
        <el-select
          v-model="formState.category"
          placeholder="请选择物品分类"
          style="width: 100%"
        >
          <el-option value="电子设备" label="电子设备" />
          <el-option value="学习用品" label="学习用品" />
          <el-option value="生活用品" label="生活用品" />
          <el-option value="证件卡片" label="证件卡片" />
          <el-option value="其他" label="其他" />
        </el-select>
      </el-form-item>

      <el-form-item label="联系方式" prop="contact_info">
        <el-input
          v-model="formState.contact_info"
          placeholder="请输入联系方式（电话/微信等）"
          :maxlength="100"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleOk">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { lostAndFoundApi } from '@/api/lostandfound.js';

const props = defineProps({
  visible: Boolean,
  item: Object,
  mode: String // 'create' | 'edit'
});

const emit = defineEmits(['update:visible', 'cancel', 'ok']);

const formRef = ref();
const confirmLoading = ref(false);

// 表单状态
const formState = reactive({
  title: '',
  description: '',
  category: '',
  contact_info: ''
});

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入物品标题', trigger: 'blur' },
    { max: 100, message: '标题不能超过100个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入物品描述', trigger: 'blur' },
    { max: 255, message: '描述不能超过255个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择物品分类', trigger: 'change' }
  ],
  contact_info: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { max: 100, message: '联系方式不能超过100个字符', trigger: 'blur' }
  ]
};

// 模态框标题
const modalTitle = computed(() => {
  return props.mode === 'create' ? '发布失物招领' : '编辑物品信息';
});

// 处理可见性变化
const handleVisibleChange = (value) => {
  emit('update:visible', value);
};

// 监听物品数据变化
watch(
  () => props.item,
  (newItem) => {
    if (newItem && props.mode === 'edit') {
      Object.keys(formState).forEach(key => {
        if (newItem[key] !== undefined) {
          formState[key] = newItem[key];
        }
      });
    }
  },
  { immediate: true }
);

// 监听可见性变化
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      // 重置表单
      nextTick(() => {
        formRef.value?.resetFields();
      });
    }
  }
);

// 确认操作
const handleOk = async () => {
  try {
    await formRef.value.validate();
    
    confirmLoading.value = true;
    
    let response;
    if (props.mode === 'create') {
      response = await lostAndFoundApi.create(formState);
    } else {
      response = await lostAndFoundApi.update(props.item.item_id, formState);
    }

    if (response.code === 0) {
      ElMessage.success(props.mode === 'create' ? '发布成功' : '更新成功');
      emit('ok');
      emit('update:visible', false);
    } else {
      ElMessage.error(response.msg || '操作失败');
    }
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息');
    } else {
      ElMessage.error('网络错误，请重试');
      console.error('操作失败:', error);
    }
  } finally {
    confirmLoading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  formRef.value?.resetFields();
  emit('update:visible', false);
  emit('cancel');
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>